<template>
  <el-dialog draggable v-model="dialog.show" width="1140px" top="50px" :before-close="handleClose" class="custom-dialog">
    <template #header> {{ props.editData.id ? '修改' : '新增' }}产品 </template>
    <el-form :model="forms" inline ref="registerRef" :rules="rules" label-width="100">
      <el-form-item label="产品编号" prop="productSerialNo">
        <el-input v-model="forms.productSerialNo" placeholder="产品编号" clearable class="width-220"></el-input>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="forms.productName" placeholder="产品名称" clearable class="width-220"></el-input>
      </el-form-item>
      <el-form-item label="产品类型" prop="productType">
        <el-radio-group v-model="forms.productType">
          <el-radio-button :label="item.value" v-for="item in productTypeData" :key="item">
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="产品分类" prop="categoryId">
        <el-tree-select
          v-model="forms.categoryId"
          default-expand-all
          highlight-current
          check-strictly
          :data="dialog.classifyOptions"
          placeholder="选择产品分类"
          @node-click="onNodeClick"
          class="width-220"
        >
        </el-tree-select>
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <z-input v-model="forms.price" placeholder="单价" clearable class="width-220"></z-input>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="forms.unit" placeholder="单位" clearable class="width-220"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="number">
        <z-input v-model="forms.number" placeholder="数量" clearable class="width-220"></z-input>
      </el-form-item>
      <el-form-item label="仓库" prop="whInfoId">
        <el-select
          class="width-220"
          v-model="forms.whInfoId"
          placeholder="请选择仓库"
          @visible-change="visWhChange"
          filterable
          remote
          clearable
          :remote-method="visWhChange"
        >
          <el-option v-for="item in selectOption.whInfo" :key="item.id" :label="item.whInfoName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="库位" prop="whInfoStorageId">
        <el-select
          class="width-220"
          v-model="forms.whInfoStorageId"
          placeholder="请选择库位"
          @visible-change="visWhStorageChange"
          filterable
          remote
          clearable
          :remote-method="visWhStorageChange"
        >
          <el-option v-for="item in selectOption.whStorage" :key="item.id" :label="item.stroageName" :value="item.id" />
        </el-select>
      </el-form-item>
      <div class="w-100 dis-flex flex-center">
        <el-form-item label="备注" prop="note" class="flex-1 flex-y-center">
          <el-input v-model="forms.note" type="textarea" placeholder="备注" clearable class="w-100"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <el-collapse-transition>
      <div v-show="!!dialog.spec.length">
        <el-alert title="产品规格" type="success" center :closable="false" class="mb-10" />
        <spec :data="dialog.spec" ref="specRef" />
      </div>
    </el-collapse-transition>
    <template #footer>
      <span class="dialog-footer">
        <z-button type="" @click="handleClose" icon="close">取消</z-button>
        <z-button icon="check" @click="onCheck" :loading="dialog.loading"> 确认 </z-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { get, post } from '@/api/index';
import { productTypeData } from '@/config/data';
import { reactive } from 'vue';
let $message = inject('$message');
let emit = defineEmits(['update:modelValue', 'onSave']);
let { dataProcess } = inject('$global');
let store = useStore();
let props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => {
      return {};
    }
  }
});
let registerRef = ref();
let specRef = ref();
let dialog = reactive({
  show: false,
  classifyOptions: [],
  spec: [],
  loading: false,
  isFirst: true
});

let selectOption = reactive({
  whSelectVisible: false,
  whInfo: [],
  whStorageSelectVisiable: false,
  whStorage: []
});

let formsInit = () => {
  return reactive({
    id: 0,
    categoryId: undefined,
    imagePaths: '',
    productSerialNo: '',
    productName: '',
    productType: 1,
    extraSpec: '',
    unit: '',
    price: 0,
    warnNumber: 0,
    statusId: 1,
    attributeValStr: '',
    note: '',
    idSorted: 0,
    customSpecValueDic: {},
    productMultiUnits: []
  });
};
let forms = formsInit();
let rules = {
  productName: [{ required: true, trigger: 'change', message: '名称不能为空!' }],
  productSerialNo: [{ required: true, trigger: 'change', message: '编号不能为空!' }],
  categoryId: [{ required: true, trigger: 'change', message: '产品分类不能为空!' }],
  productType: [{ required: true, trigger: 'change', message: '产品类型不能为空!' }]
};
let categorys = computed(() => store.state.categorys);
watch(
  () => props.modelValue,
  async val => {
    dialog.show = val;
    if (!val) return;
    // 看产品分类有没有数据
    if (!categorys.value.length) await store.dispatch('getCategory');
    dialog.classifyOptions = dataProcess(categorys.value, 'categoryParentId')[0].children;
    if (props.editData.id) {
      getDetail();
      return;
    }
    dialog.spec = [];
    const formData = formsInit();
    Object.keys(formData).map(r => {
      forms[r] = props.editData[r] != undefined ? props.editData[r] : formData[r];
    });
  },
  {
    immediate: true
  }
);
// 关闭
const handleClose = () => {
  registerRef.value.resetFields();
  emit('update:modelValue', false);
};
// 确认
const onCheck = async () => {
  if (!registerRef.value) return;
  registerRef.value.validate(async val => {
    if (!val) return;
    let specCheck = dialog.spec.length ? await specRef.value.check() : true;
    if (!specCheck) return;
    try {
      dialog.loading = true;
      await post('Product/CreateOrUpdate', { ...forms, customSpecValueDic: specCheck });
      $message.success(`${props.editData.id ? '修改' : '新增'}成功`);
      dialog.loading = false;
      emit('onSave');
      registerRef.value.resetFields();
    } catch (error) {
      console.log('DeptMent/AddOrUpdate错误', error);
      dialog.loading = false;
    }
  });
};
// 点击产品分类
const onNodeClick = val => {
  getSpecList(val.id);
};
// 获取规格
const getSpecList = async id => {
  let { result } = await post('CustomCategorySpec/GetList', { pageSize: 999, pageIndex: 1, categoryId: id, isNotContain: false });
  dialog.spec = result.items;
};
// 详情接口
const getDetail = async () => {
  let { result } = await get('Product/GetModel', { id: props.editData.id });
  const formData = formsInit();
  Object.keys(formData).map(r => {
    forms[r] = result[r] != undefined ? result[r] : formData[r];
  });
  dialog.spec = result.customObjectValues;
};

// 库存下拉及联想触发
const visWhChange = val => {
  console.log('val', val);
  if (val === true) {
    selectOption.whSelectVisible = val;
    onWhInfoSel();
  } else if (val !== false && val !== '' && selectOption.whSelectVisible) onWhInfoSel(val);
  else selectOption.whSelectVisible = val;
};

// 库位下拉或联想触发
const visWhStorageChange = val => {
  if (val === true) {
    selectOption.whStorageSelectVisiable = val;
    onWhInfoSel();
  } else if (val !== false && val !== '' && selectOption.whStorageSelectVisiable) onWhStorageSel(val);
  else selectOption.whStorageSelectVisiable = val;
};

// 查询所有启用的仓库
const onWhInfoSel = async (keyWord = '') => {
  const { result } = await post('WhInfo/GetList', { keyWord: keyWord, statusId: 1 });
  selectOption.whInfo = result;
};
// 查询所有启用的仓库
const onWhStorageSel = async (keyWord = '') => {
  const { result } = await post('WhInfoStorage/GetList', { whInfoId: forms.whInfoId, keyWord: keyWord, statusId: 1 });
  selectOption.whStorage = result;
};
</script>

<style lang="scss" scoped>
.unit {
  position: relative;

  :deep(.unit-button) {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>
